package dwz.business.lotto.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import dwz.business.lotto.YongHuInterface;
import dwz.business.lotto.ZhuDanInterface;
import dwz.common.util.BuildOrderCode;
import dwz.common.util.CheckNumberType;
import dwz.common.util.MD5Util;
import dwz.common.util.web.PageInfo;
import dwz.framework.sys.exception.SystemClosedException;
import dwz.persistence.beans.CanShuSheZhi;
import dwz.persistence.beans.CanShuSheZhiExample;
import dwz.persistence.beans.DingDan;
import dwz.persistence.beans.HuiYuanSheZhi;
import dwz.persistence.beans.HuiYuanSheZhiExample;
import dwz.persistence.beans.QiHao;
import dwz.persistence.beans.QiHaoExample;
import dwz.persistence.beans.WeiChongGongHaoMa;
import dwz.persistence.beans.YongHu;
import dwz.persistence.beans.YongHuExample;
import dwz.persistence.beans.ZhuDan;
import dwz.persistence.beans.ZhuDanExample;
import dwz.persistence.beans.QiHaoExample.Criteria;
import dwz.persistence.mapper.CanShuSheZhiMapper;
import dwz.persistence.mapper.DingDanMapper;
import dwz.persistence.mapper.HuiYuanSheZhiMapper;
import dwz.persistence.mapper.QiHaoMapper;
import dwz.persistence.mapper.WeiChongGongHaoMaMapper;
import dwz.persistence.mapper.YongHuMapper;
import dwz.persistence.mapper.ZhuDanMapper;
import dwz.web.vo.GeJiInfo;
import dwz.web.vo.GeJiInfoCondition;
import dwz.web.vo.Ids;
import dwz.web.vo.YiChiCondition;
import dwz.web.vo.YonghuVo;
import dwz.web.vo.ZhuDanVo;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Transactional(rollbackFor = Exception.class)
@Service
public class YongHuInterfaceImpl implements YongHuInterface{
	@Autowired
	YongHuMapper yongHuMapper;
	@Autowired
	QiHaoMapper qiHaoMapper;
	@Autowired
	DingDanMapper danMapper;
	@Autowired
	ZhuDanMapper zhuDanMapper;
	@Autowired
	CanShuSheZhiMapper canShuSheZhiMapper;
	@Autowired
	HuiYuanSheZhiMapper huiYuanSheZhiMapper;
	@Autowired
	WeiChongGongHaoMaMapper weiChongGongHaoMaMapper;
	@Autowired
	ZhuDanInterface zhuDanInterface;
	
	
	@Override
	public int countByExample(YongHuExample example) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int deleteByExample(YongHuExample example) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int deleteByPrimaryKey(Integer id) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int insertSelective(YongHu record) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public List<YongHu> selectByExample(YongHuExample example) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<YongHu> selectByExampleWithPage(YongHuExample example,
			PageInfo pageInfo) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public YongHu selectByPrimaryKey(Integer id) {
		// TODO Auto-generated method stub
		return yongHuMapper.selectByPrimaryKey(id);
	}

	@Override
	public int updateByPrimaryKeySelective(YongHu entity) {
		yongHuMapper.updateByPrimaryKeySelective(entity);
		return 0;
	}

	@Override
	public List<YongHu> selectAllWithPage(YongHu entity, PageInfo pageInfo) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public YongHu selectEntityByExample(YongHuExample example) {
		YongHu yongHu = null;
		List<YongHu> yongHus = yongHuMapper.selectByExample(example);
		if(yongHus != null && yongHus.size() == 1){
			yongHu = yongHus.get(0);
		}
		return yongHu;
	}

	@Override
	public void xiaZhu(Integer userId, String[] haomas,Float jinEr,String ip) throws Exception{
		//1判断是否关盘
		QiHao qiHao = huoQuDangQianQiHao();
		// 获取当前期号
		Integer dangQianQiHao = qiHao.getQh_j();
		
		if(isClose(qiHao)){
			throw new SystemClosedException("系统已经关盘");
		}
		//构造出一个赔率设置map 后续对每一个号码就不用每次都查询数据库。
		CanShuSheZhiExample canShuSheZhiExample = new CanShuSheZhiExample();
		List<CanShuSheZhi> canShuSheZhis = canShuSheZhiMapper.selectByExample(canShuSheZhiExample);
		
		
		Map<Integer,List<String>> map = new HashMap<Integer, List<String>>();
		for(CanShuSheZhi canShuSheZhi : canShuSheZhis){
			List<String> strings = new ArrayList<String>();
			strings.add(canShuSheZhi.getPlsx_j());//赔率上限
			strings.add(canShuSheZhi.getDxsx_j()+"");//单项上限
			strings.add(canShuSheZhi.getDzsx_j()+"");//单注上限
			strings.add(canShuSheZhi.getZxxz_j()+""); //最小下注
			map.put(canShuSheZhi.getLx_j(), strings);
		}
		//2生成注单号号码，
		String orderString = BuildOrderCode.buildOrderCode(userId);
		
		DingDan dingDan = new DingDan();
		dingDan.setYh_id_j(userId);
		dingDan.setDdh_j(orderString);
		dingDan.setXdsj_j(new Date());
		dingDan.setQh_j(dangQianQiHao+"");
		danMapper.insertSelective(dingDan);
		//获取订单的ID
		int dingdanId = dingDan.getId();
		//3拉取金额
		YongHu yongHu = yongHuMapper.selectByPrimaryKey(userId);
		Float yuEr = yongHu.getYe_j();
		//构造出一个用户设置的map 
		HuiYuanSheZhiExample huiYuanSheZhiExample = new HuiYuanSheZhiExample();
		huiYuanSheZhiExample.createCriteria().andYh_id_jEqualTo(yongHu.getId());
		List<HuiYuanSheZhi> huiYuanSheZhis = huiYuanSheZhiMapper.selectByExample(huiYuanSheZhiExample);
		Map<Integer,List<String>> mapSheZhi = new HashMap<Integer, List<String>>();
		
		for(HuiYuanSheZhi huiYuanSheZhi : huiYuanSheZhis){
			List<String> strings = new ArrayList<String>();
			strings.add(huiYuanSheZhi.getZjhs_j()+"");//自己回水
			strings.add(huiYuanSheZhi.getZjpl_j()+"");//自己赔率
			strings.add(huiYuanSheZhi.getDlzs_j()+"");//代理赚水
			strings.add(huiYuanSheZhi.getDlpl_j()+""); //代理赔率
			mapSheZhi.put(huiYuanSheZhi.getLx_j(), strings);
		}
		
		//遍历号码
		for(String haoma : haomas){
			//4判断号码类型
			if(haoma!=null && !haoma.equals("")){
				int typeId = CheckNumberType.check(haoma);
				ZhuDan zhuDan = new ZhuDan();
				zhuDan.setDd_id_j(dingdanId);
				zhuDan.setDdh_j(orderString);
				zhuDan.setQh_j(dangQianQiHao);
				zhuDan.setHm_j(haoma);
				zhuDan.setLx_j(typeId+"");
				//判断最小下注金额
				//判断是否超出了单注上限------
				//判断是否超出了单项上限 ------
				ZhuDanExample zhuDanExample = new ZhuDanExample();
				zhuDanExample.createCriteria().andQh_jEqualTo(dangQianQiHao).andLx_jEqualTo(typeId+"").andSftm_jEqualTo(0);
				Float dangQianSuoyouXianzhu = zhuDanMapper.selectDanXiangShangxian(zhuDanExample);
				if(dangQianSuoyouXianzhu == null ){
					dangQianSuoyouXianzhu = 0.0f;
				}
				if(		(yuEr-jinEr) >= 0  //余额是否大于下注金额
						&& jinEr >= Float.parseFloat(map.get(typeId).get(3)) //大于最小下注
						&& jinEr <= Float.parseFloat(map.get(typeId).get(2)) //小于单注上限
						&& (dangQianSuoyouXianzhu+jinEr) <= Float.parseFloat(map.get(typeId).get(1)) //小于单项上限
						
						){
					zhuDan.setJe_j(jinEr);
					yuEr = yuEr -jinEr;
					zhuDan.setSftm_j(0);
					zhuDan.setSfzj_j(0);
					
					//设置自己设置的回水及赔率和代理赚水和赔率
					// TODO 如果是2 3 4 字现的话 就还要去判断类型 以便查询 多个用 分开的赔率
					
					// TODO 如果这些号码处于固定赔率表中 那么 按照固定赔率表中的赔率设置。
					
					zhuDan.setHs_j(Float.parseFloat(mapSheZhi.get(typeId).get(0)));
					zhuDan.setPl_j(mapSheZhi.get(typeId).get(1));
					zhuDan.setDlzs_j(mapSheZhi.get(typeId).get(2));
					zhuDan.setDlpl_j(mapSheZhi.get(typeId).get(3));
					zhuDan.setIp_j(ip);
					
					
					Ids ids = yongHuMapper.selectAllIds(userId);
					zhuDan.setYh_id(ids.getUserId());
					zhuDan.setDl_id(ids.getDaiLiId());
					zhuDan.setZdl_id(ids.getZongDaiLiId());
					zhuDan.setGd_id(ids.getGuDongId());
					zhuDan.setDgd_id(ids.getDaGuDongId());
					zhuDan.setZj_id(ids.getZongJianId());
					
					
					// 向上寻址到 大股东 （因为总监的初始占成和回水是设置到下一级里面的）设置每一级的占成，比例，赚水（回水），赔率
					GeJiInfoCondition geJiInfoCondition = new GeJiInfoCondition();
					geJiInfoCondition.setLx(typeId);
					
					int[] midids = new int[4];
					midids[0] = ids.getDaiLiId();
					midids[1] = ids.getZongDaiLiId();
					midids[2] = ids.getGuDongId();
					midids[3] = ids.getDaGuDongId();
					geJiInfoCondition.setIds(midids);
					
					List<GeJiInfo> geJiInfos = yongHuMapper.selectGeJiInfo(geJiInfoCondition);
					
					//构建一个map
					Map<Integer, GeJiInfo> geJiMap = new HashMap<Integer, GeJiInfo>();
					
					
					
					
					//开始设置，总代理的回水和赔率是设置在代理身上的 依次类推  并顺便构建出一个map
					for(GeJiInfo geJiInfo : geJiInfos){
						if(geJiInfo.getId() == ids.getDaiLiId()){
							zhuDan.setDl_zcbl(geJiInfo.getZc());
							zhuDan.setDl_zcsx(geJiInfo.getZcfxsx());
							zhuDan.setZdl_hs(geJiInfo.getSjzs());
							zhuDan.setZdl_pl(geJiInfo.getSjpl());
						}else if(geJiInfo.getId() == ids.getZongDaiLiId()){
							zhuDan.setZdl_zcbl(geJiInfo.getZc());
							zhuDan.setZdl_zcsx(geJiInfo.getZcfxsx());
							zhuDan.setGd_hs(geJiInfo.getSjzs());
							zhuDan.setGd_pl(geJiInfo.getSjpl());
						}else if(geJiInfo.getId() == ids.getGuDongId()){
							zhuDan.setGd_zcbl(geJiInfo.getZc());
							zhuDan.setGd_zcsx(geJiInfo.getZcfxsx());
							zhuDan.setDgd_hs(geJiInfo.getSjzs());
							zhuDan.setDgd_pl(geJiInfo.getSjpl());
						}else if(geJiInfo.getId() == ids.getDaGuDongId()){
							zhuDan.setDgd_zcbl(geJiInfo.getZc());
							zhuDan.setDgd_zcsx(geJiInfo.getZcfxsx());
							zhuDan.setZj_hs(geJiInfo.getSjzs());
							zhuDan.setZj_pl(geJiInfo.getSjpl());
						}
						geJiMap.put(geJiInfo.getId(), geJiInfo);
					}
					
					
						
					// 完成   要计算是否吃满 因此要根据占成 和 占成的 最大数值 还有 金额 给计算出来 每一级占这个号码多少钱。
						//cizhujiner
						//1 sum 这个类型everyLevel的总和
						//2    计算 占这个号码  的金额
						//3	判断 +这个金额 是否超出了最大占成风险
							//3.1 如果没有超过 则更新金额 cizhujiner-chi
							     //剩余的全给zj
							//3.2 如果超过 则抛给上一级
					            //剩余的全给zj
					
					float dailichihou = checkChiJinEr( ids.getDaiLiId(), zhuDan, jinEr,jinEr, geJiMap.get(ids.getDaiLiId()).getZcfxsx(), typeId, YiChiCondition.DLID, YiChiCondition.DLCHI, geJiMap.get(ids.getDaiLiId()).getZc());
					float zdailichihou = checkChiJinEr( ids.getZongDaiLiId(), zhuDan, jinEr,dailichihou, geJiMap.get(ids.getZongDaiLiId()).getZcfxsx(), typeId, YiChiCondition.ZDLID, YiChiCondition.ZDLCHI, geJiMap.get(ids.getZongDaiLiId()).getZc());
					float gudongchihou = checkChiJinEr( ids.getGuDongId(), zhuDan, jinEr,zdailichihou, geJiMap.get(ids.getGuDongId()).getZcfxsx(), typeId, YiChiCondition.GDID, YiChiCondition.GDCHI, geJiMap.get(ids.getGuDongId()).getZc());
					//等大股东吃完 剩下的都给总监了
					Float chiHouYuErFloat = checkChiJinEr( ids.getDaGuDongId(), zhuDan, jinEr,gudongchihou, geJiMap.get(ids.getDaGuDongId()).getZcfxsx(), typeId, YiChiCondition.DGDID, YiChiCondition.DGDCHI, geJiMap.get(ids.getDaGuDongId()).getZc());
					zhuDan.setZj_chi(chiHouYuErFloat);
					
					
					
					
					
					
					
					
					
					
					//插入号码
					zhuDanMapper.insertSelective(zhuDan);
					
					
				}else {
					//处理失败的号码
					
					System.out.println(haoma+"----------------->>>>>");
					WeiChongGongHaoMa weiChongGongHaoMa = new WeiChongGongHaoMa();
					weiChongGongHaoMa.setHm_j(haoma);
					weiChongGongHaoMa.setQh_j(dangQianQiHao);
					weiChongGongHaoMa.setYh_id_j(yongHu.getId());
					weiChongGongHaoMaMapper.insertSelective(weiChongGongHaoMa);
				}
				
				yongHu.setYe_j(yuEr);
				//10减少会员金额
				yongHuMapper.updateByPrimaryKeySelective(yongHu);
			}
			
			
			
			
		}
		
		
		
		
	
	
		
		//11 升降水。
		//
		
	}
	
	
	
	/**
	 * 
	 * @param userId      id
	 * @param zhuDan	  注单
	 * @param ciZhuJinEr  此注号码的金额
	 * @param ciHouYuEr   各级吃后的余额
	 * @param zcfxsx     各级占成风险上限
	 * @param hmlx     号码类型
	 * @param userIdCol  各级代理的用户数据库字段名
	 * @param userChiCol 各级
	 * @param czbl bili
	 * @return
	 */
	private float checkChiJinEr(int userId, ZhuDan zhuDan,float ciZhuJinEr,float ciHouYuEr,float zcfxsx,int hmlx,String userIdCol,String userChiCol,int czbl){
		// TODO 要计算是否吃满 因此要根据占成 和 占成的 最大数值 还有 金额 给计算出来 每一级占这个号码多少钱。
		//cizhujiner
		//1 sum 这个类型everyLevel的总和
		//2    计算 占这个号码  的金额
		//3	判断 +这个金额 是否超出了最大占成风险
			//3.1 如果没有超过 则更新金额 cizhujiner-chi
			     //剩余的全给zj
			//3.2 如果超过 则抛给上一级
	            //剩余的全给zj
		
		
		float chiHouYuEr = ciHouYuEr;
		YiChiCondition yiChiCondition = new YiChiCondition();
		yiChiCondition.setChiColName(userChiCol);
		yiChiCondition.setLx(hmlx);
		yiChiCondition.setUserId(userId);
		yiChiCondition.setUserIdColName(userIdCol);
		//这里使用zhuDanInterface而不是 zhuDanMapper 是因为 zhuDanInterface包装的selectDaiLiYiChiMoney方法对null值进行了处理
		//为了保险起见 最好将各级吃的数据库初始值设置为0.00
		float current = zhuDanInterface.selectDaiLiYiChiMoney(yiChiCondition);
		if(current+ciZhuJinEr*czbl/10 < zcfxsx){
			if(userChiCol.equals(YiChiCondition.DLCHI)){
				zhuDan.setDl_chi(ciZhuJinEr*czbl/10);
				chiHouYuEr -= ciZhuJinEr*czbl/10;
			}else if(userChiCol.equals(YiChiCondition.ZDLCHI)){
				zhuDan.setZdl_chi(ciZhuJinEr*czbl/10);
				chiHouYuEr -= ciZhuJinEr*czbl/10;
			}else if(userChiCol.equals(YiChiCondition.GDCHI)){
				zhuDan.setGd_chi(ciZhuJinEr*czbl/10);
				chiHouYuEr -= ciZhuJinEr*czbl/10;
			}else if(userChiCol.equals(YiChiCondition.DGDCHI)){
				zhuDan.setDgd_chi(ciZhuJinEr*czbl/10);
				chiHouYuEr -= ciZhuJinEr*czbl/10;
			}
		}
		return chiHouYuEr;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	@Override
	public void tuiMa(Integer userId, Integer[] haomasIds) throws Exception{
		//1判断是否关盘
		QiHao qiHao = huoQuDangQianQiHao();
		if(isClose(qiHao)){
			throw new Exception("系统已经关盘");
		}
		//2退码 （更新状态)
		YongHu yongHu = yongHuMapper.selectByPrimaryKey(userId);
		Float jinEr = yongHu.getYe_j();
		//这里可以优化一下 改成 select sum(je_j) from tb where userid = "" and  ids in() ,
		for(Integer id : haomasIds){			
			ZhuDan zhuDan = zhuDanMapper.selectByPrimaryKey(id);
			Float zhudanJinEr = zhuDan.getJe_j();
			jinEr += zhudanJinEr;
			zhuDan.setSftm_j(1);
			zhuDanMapper.updateByPrimaryKeySelective(zhuDan);
			//TODO 向上寻址各个代理的金额然后扣除掉占成的金额。
		}
		yongHu.setYe_j(jinEr);
		// 3增加金额
		yongHuMapper.updateByPrimaryKeySelective(yongHu);
		
		
	}
	
	/**
	 * 判断当前时间是否已经错过了关盘时间
	 * @return
	 * @throws Exception
	 */
	
	
	
	private boolean isClose(QiHao qiHao) throws Exception{
		//判断当前时间是否大于关盘时间
		Date date = qiHao.getGpsj_j();
		return new Date().after(date);
		
		
	}
	
	/**
	 * 得到当前期号 以空值作为判断条件
	 * @return
	 */
	private QiHao huoQuDangQianQiHao(){
		
		return qiHaoMapper.selectMaxQiHao();
	}
	
	
	
	

	@Override
	public void deleteUnsuccessfulNumber(Integer[] haomasIds) {
		//批量删除吧	
		weiChongGongHaoMaMapper.batchDeleteById(haomasIds);
	}
	
	
	
	
	
	
public void test(){		
		QiHaoExample qiHaoExample = new QiHaoExample();		
		Criteria criteria = qiHaoExample.createCriteria();
		criteria.andKjhm_jIsNull();
	//	QiHao qiHao = qiHaoMapper.se(qiHaoExample);
	}

@Override
public YongHu findUserById(Integer userId) throws Exception {
	
	return yongHuMapper.selectByPrimaryKey(userId);
}

@Override
public boolean isValidateUser(String userName, String password) {
	boolean isValidateUser = false;
	YongHuExample yongHuExample = new YongHuExample();
	yongHuExample.createCriteria().andYhm_jEqualTo(userName).andMm_jEqualTo(MD5Util.MD5(password));
	YongHu yongHu = yongHuMapper.selectEntityByExample(yongHuExample);
	if(yongHu != null && yongHu.getSfty_j() == 0){
		isValidateUser = true;
	}
	
	
	
	
	return isValidateUser;
}

@Override
public String modifyPassword(Integer userId,String oldPassword, String newPasswor) {
	YongHu yongHu = yongHuMapper.selectByPrimaryKey(userId);
	String password = yongHu.getMm_j();
	if(!MD5Util.MD5(oldPassword).equals(password)){
		return "旧密码不正确";
	}else{
		//String[] invalidatePass = new String
		Map<String, String> map = new HashMap<String, String>();
		map.put("a12345", "a12345");
		map.put("ab1234", "ab1234");
		map.put("abc123", "abc123");
		
		map.put("a1b2c3", "a1b2c3");
		map.put("aaa111", "aaa111");
		map.put("123qwe", "123qwe");

		if(map.containsKey(newPasswor)){
			return "不能使用以下密码:a12345	 ，ab1234	 ，abc123	 ，a1b2c3	 ，aaa111	 ，123qwe";
		}else {
			yongHu.setMm_j(MD5Util.MD5(newPasswor));
			yongHu.setSfxgg_j(1);
			yongHuMapper.updateByPrimaryKey(yongHu);
			return "修改密码成功";
		}
		
		
	}
	
	
	
}

@Override
public Ids selectAllIds(int userid) {
	
	return yongHuMapper.selectAllIds(userid);
}
}
